package cn.xxx.org.controller;

import cn.xxx.basic.util.AjaxResult;
import cn.xxx.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传文件统一接口
 *  上传接口
 *  删除接口
 *  修改 = 删除+上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * 上传接口
     * @param file 使用@RequestPart 申明，可以直接完成空校验
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file", required = true) MultipartFile file){
        try {
            //获取扩展名
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess("上传失败！"+e.getMessage());
        }
    }

    /**
     * 删除接口
     * @param path 使用@RequestPart 申明，可以直接完成空校验
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestPart(value = "path", required = true) String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);

            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess("删除失败！"+e.getMessage());
        }
    }
}
